package com.dianmi.seckill.common.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xieqiaofu
 * @date 2020/11/24
 */
@Slf4j
@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public ResponseData handleException(Throwable e) {
        if (e instanceof ServiceException) {
            return ResponseData.failed(((ServiceException) e).getCode(), e.getMessage());

        }
        log.error("系统异常", e);
        return ResponseData.failed(ResponseCode.SERVICE_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public ResponseData handleBindException(Exception e) {
        BindingResult bindingResult = null;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        }
        if (bindingResult != null && bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            String errorMsg = fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));
            return ResponseData.failed(ResponseCode.SERVICE_ERROR.getCode(), errorMsg);
        }
        log.error("参数绑定错误", e);
        return ResponseData.failed(ResponseCode.SERVICE_ERROR.getCode(), "参数绑定错误");
    }
}
